import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/question.dart';
import '../services/wrong_question_provider.dart';
import 'question_detail_screen.dart';

class WrongQuestionsScreen extends StatefulWidget {
  final int rank;
  final int type;
  final String title;

  const WrongQuestionsScreen({
    Key? key,
    required this.rank,
    required this.type,
    required this.title,
  }) : super(key: key);

  @override
  State<WrongQuestionsScreen> createState() => _WrongQuestionsScreenState();
}

class _WrongQuestionsScreenState extends State<WrongQuestionsScreen> {
  late WrongQuestionProvider _wrongQuestionProvider;

  @override
  void initState() {
    super.initState();
    _wrongQuestionProvider =
        Provider.of<WrongQuestionProvider>(context, listen: false);
    _loadWrongQuestions();
  }

  Future<void> _loadWrongQuestions() async {
    await _wrongQuestionProvider.loadWrongQuestions(widget.rank, widget.type);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('${widget.title}错题集'),
        backgroundColor: Theme.of(context).colorScheme.primary,
        foregroundColor: Colors.white,
      ),
      body: Consumer<WrongQuestionProvider>(
        builder: (context, provider, child) {
          print(
              "WrongQuestionsScreen: isLoading=${provider.isLoading}, hasError=${provider.hasError}, wrongQuestions=${provider.wrongQuestions.length}");

          if (provider.isLoading) {
            return const Center(child: CircularProgressIndicator());
          }

          if (provider.hasError) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Icon(Icons.error_outline, size: 60, color: Colors.red),
                  const SizedBox(height: 16),
                  Text('加载失败: ${provider.errorMessage}',
                      textAlign: TextAlign.center),
                  const SizedBox(height: 16),
                  ElevatedButton(
                    onPressed: _loadWrongQuestions,
                    child: const Text('重试'),
                  ),
                ],
              ),
            );
          }

          if (provider.wrongQuestions.isEmpty) {
            return const Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.check_circle_outline,
                      size: 60, color: Colors.green),
                  SizedBox(height: 16),
                  Text('暂无错题，继续加油！', style: TextStyle(fontSize: 16)),
                ],
              ),
            );
          }

          return RefreshIndicator(
            onRefresh: _loadWrongQuestions,
            child: ListView.builder(
              padding: const EdgeInsets.all(16),
              itemCount: provider.wrongQuestions.length,
              itemBuilder: (context, index) {
                final question = provider.wrongQuestions[index];
                return _buildQuestionCard(context, question, provider);
              },
            ),
          );
        },
      ),
    );
  }

  Widget _buildQuestionCard(
      BuildContext context, Question question, WrongQuestionProvider provider) {
    return Dismissible(
      key: Key('wrong_question_${question.id}'),
      background: Container(
        color: Colors.red,
        alignment: Alignment.centerRight,
        padding: const EdgeInsets.only(right: 20.0),
        child: const Icon(Icons.delete, color: Colors.white),
      ),
      direction: DismissDirection.endToStart,
      confirmDismiss: (direction) async {
        return await showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: const Text('确认移除'),
              content: const Text('确定要从错题集中移除此题吗？'),
              actions: <Widget>[
                TextButton(
                  onPressed: () => Navigator.of(context).pop(false),
                  child: const Text('取消'),
                ),
                TextButton(
                  onPressed: () => Navigator.of(context).pop(true),
                  child: const Text('确定'),
                ),
              ],
            );
          },
        );
      },
      onDismissed: (direction) {
        provider.removeFromWrongQuestions(question.id);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('已从错题集中移除题目 ${question.id}')),
        );
      },
      child: Card(
        margin: const EdgeInsets.only(bottom: 16),
        elevation: 2,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        child: InkWell(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => QuestionDetailScreen(
                  question: question,
                  isFromWrongQuestions: true,
                ),
              ),
            ).then((_) => _loadWrongQuestions());
          },
          borderRadius: BorderRadius.circular(12),
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 8, vertical: 4),
                      decoration: BoxDecoration(
                        color: Theme.of(context).colorScheme.primary,
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: Text(
                        question.questionTypeText,
                        style:
                            const TextStyle(color: Colors.white, fontSize: 12),
                      ),
                    ),
                    const SizedBox(width: 8),
                    Text(
                      '题号: ${question.id}',
                      style: TextStyle(color: Colors.grey[600], fontSize: 12),
                    ),
                    const Spacer(),
                    const Icon(Icons.error, color: Colors.red, size: 20),
                  ],
                ),
                const SizedBox(height: 12),
                Text(
                  question.title,
                  style: const TextStyle(fontSize: 16),
                ),
                if (question.titlePic.isNotEmpty) ...[
                  const SizedBox(height: 12),
                  Center(
                    child: Image.network(
                      question.titlePic,
                      errorBuilder: (context, error, stackTrace) {
                        return const Icon(Icons.broken_image, size: 100);
                      },
                      loadingBuilder: (context, child, loadingProgress) {
                        if (loadingProgress == null) return child;
                        return const Center(
                          child: CircularProgressIndicator(),
                        );
                      },
                    ),
                  ),
                ],
              ],
            ),
          ),
        ),
      ),
    );
  }
}
